package org.deng.learn.webflux.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * @author 邓力宾
 * @date 2020/12/18 14:17
 * @desc
 */
@RestController
@RequestMapping("/demo")
@Slf4j
public class DemoController {

    /**
     * 使用spring mvc模式
     * @return
     */
    @GetMapping("/test1")
    public String test1(){
        log.info("test1 start::");
        String str = createStr(); //耗时多久 就会阻塞多久
        log.info("test1 end::");
        return str;
    }

    /**
     * 使用webflux mono 0到1个元素
     * @return
     */
    @GetMapping("/test2")
    public Mono<String> test2(){
        //return Mono.just("test2");
        log.info("test2 start::");
        Mono<String> mono = Mono.fromSupplier(this::createStr);
        log.info("test2 end::"); //不会阻塞
        return mono;
    }

    /**
     * 使用webflux flux:0到n个元素 依次返回n个数据
     * @return
     */
    @GetMapping(value = "/test3", produces = MediaType.TEXT_EVENT_STREAM_VALUE) //Content-Type: text/event-stream;charset=UTF-8
    public Flux<String> test3(){
        Flux<String> flux = Flux.fromStream(IntStream.range(1, 10).mapToObj(i->
            createStr() + i
        ));
        return flux;
    }


    /**
     * 模拟耗时操作
     * @return
     */
    private String createStr(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "data";
    }
}
